<template>
  <div class="flex flex-wrap gap-4 items-center">
    <el-select
      clearable
      style="width: 240px"
      placeholder="请选择省份"
      v-model="province"
    >
      <el-option
        v-for="item in areas"
        :key="item.code"
        :value="item.code"
        :label="item.name"
        >{{ item.name }}</el-option
      >
    </el-select>
    <el-select
      clearable
      :disabled="!province"
      placeholder="请选择城市"
      v-model="city"
    >
      <el-option
        v-for="item in cityList"
        :key="item.code"
        :value="item.code"
        :label="item.name"
        >{{ item.name }}</el-option
      >
    </el-select>
    <el-select
      clearable
      :disabled="!province || !city"
      placeholder="请选择区域"
      v-model="area"
    >
      <el-option
        v-for="item in areaList"
        :key="item.code"
        :value="item.code"
        :label="item.name"
        >{{ item.name }}</el-option
      >
    </el-select>
  </div>
</template>

<script setup lang="ts">
import { watch, ref } from 'vue'
import allAreas from '../lib/pca-code.json'

export interface AreaItem {
  name: string
  code: string
  children?: AreaItem[]
}

export interface AreaData {
  name: string
  code: string
}

const province = ref<string>('')
const city = ref<string>('')
const area = ref<string>('')
const areas = ref(allAreas)
const cityList = ref<AreaItem[]>([])
const areaList = ref<AreaItem[]>([])

// 分发时间给父组件
const emits = defineEmits(['change'])

watch(
  () => province.value,
  (val) => {
    if (val) {
      const cities = areas.value.find((item) => item.code === province.value)
        ?.children!
      cityList.value = cities
    }
    city.value = ''
    area.value = ''
  }
)

watch(
  () => city.value,
  (val) => {
    if (val) {
      const areaArr = cityList.value?.find((item) => item.code === city.value)
        ?.children!
      areaList.value = areaArr
    }
    area.value = ''
  }
)

watch(
  () => area.value,
  (val) => {
    if (!val) return
    const provinceData: AreaData = {
      code: province.value,
      name:
        province.value &&
        allAreas.find((item) => item.code === province.value)!.name,
    }
    const cityData: AreaData = {
      code: city.value,
      name:
        city.value &&
        cityList.value.find((item) => item.code === city.value)!.name,
    }
    const areaData: AreaData = {
      code: val,
      name: val && areaList.value.find((item) => item.code === val)!.name,
    }

    emits('change', {
      province: provinceData,
      city: cityData,
      area: areaData,
    })
  }
)
</script>

<style scoped lang="scss"></style>
